package spike.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by ylyang on 06/04/2017.
 */
public class FileUtils {
    public static class ReaderUtils {
        public static String readLineFromFile(String name) {
            return readStream(name).reduce("", (l, r) -> l + " " + r);
        }

        public static List<String> readListFromFile(String name) {
            return readStream(name).collect(Collectors.toList());
        }

        private static Stream<String> readStream(String name) {
            InputStream resourceAsStream = FileUtils.class.getResourceAsStream(name);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resourceAsStream));
            return bufferedReader.lines();
        }
    }

    public static class WriterUtils {
        public static boolean writeLine(String pathname, String s, boolean append) {
            ArrayList<String> strings = new ArrayList<String>() {{
                add(s);
            }};

            return writeLines(pathname, strings, append);
        }

        public static boolean writeLines(String pathname, List<String> strings, boolean append) {
            try {
                File file = new File(pathname);
                if (!file.exists()) {
                    return false;
                }

                FileWriter fw = new FileWriter(file, append);
                for (String s : strings) {
                    fw.write(s);
                    fw.write(System.lineSeparator());
                }

                fw.flush();
                fw.close();

                return true;
            } catch (Exception e) {
                return false;
            }
        }
    }

    public static class PathUtils {
        public static String getResourcePath(String name) {
            return FileUtils.class.getResource(name).getPath();
        }
    }
}
